<template>
  <BasicVxeModal
    v-bind="$attrs"
    :width="860"
    :height="580"
    :title="t('custom.调整系数')"
    :show-maximize="false"
    :show-footer="false"
    @register="registerModal"
  >
    <div class="modal-container">
      <BasicVxeTable ref="gridRef" v-bind="gridOption" stripe>
        <template #rovingRenewCoefficientSlot="{ row }">
          <el-input-number
            size="small"
            :controls="false"
            v-model="row.rovingRenewCoefficient"
            @change="handleChange(row)"
          />
        </template>
      </BasicVxeTable>
    </div>
  </BasicVxeModal>
</template>

<script setup lang="ts">
  import { useVxeModalInner } from '@/components/ui/vxe-modal'
  import { ElMessage } from 'element-plus'
  import { UNIT_LIST } from '@/utils/constants/common'
  import { getWuLiaoList, postGengXinWuLiao } from '@/api/shengChanSheZhi'
  import { useUserStore } from '@/store/modules/user'

  const { t } = useI18n()
  const gridRef = ref<BasicGridInstance>()
  const columns: BasicGridColumnProps[] = [
    {
      title: '物料名称',
      field: 'name',
      align: 'center'
    },
    {
      title: '纱支',
      field: 'yarnCount',
      align: 'center'
    },
    {
      title: '定量',
      field: 'weightPerLength',
      align: 'center'
    },
    {
      title: '换段预测调整系数',
      field: 'rovingRenewCoefficient',
      slots: { default: 'rovingRenewCoefficientSlot' },
      align: 'center'
    }
  ]

  const gridOption = reactive<BasicGridProps>({
    maxHeight: 520,
    proxyConfig: {
      autoLoad: false,
      showLoading: false, // 关闭加载中
      ajax: {
        query: () => {
          // 默认接收 Promise<any[]>
          return getInfo()
        }
      }
    },
    columns: columns
  })

  const handleChange = (item) => {
    postGengXinWuLiao(item, item.id)
      .then(() => {
        ElMessage.success('修改成功!')
      })
      .catch(() => {})
  }

  const userStore = useUserStore()
  const pid = userStore.getSycConstant('xiShaID')
  const infoList = ref()
  const [registerModal, { setModalProps }] = useVxeModalInner(async (_data) => {
    setModalProps({ loading: true })
    gridRef.value?.$grid?.commitProxy('query')
  })

  const getInfo = () => {
    return new Promise<any[]>((resolve) => {
      getWuLiaoList(pid, '').then((res: any) => {
        setModalProps({ loading: false })
        infoList.value = res
        resolve(
          res.map((item) => {
            item.weightPerLengthUnit =
              UNIT_LIST.find((val) => (val.value = item.weightPerLengthUnit))?.label || ''
            return item
          })
        )
      })
    })
  }
</script>

<style lang="scss" scoped>
  :deep(.el-input-number) {
    width: 100%;

    input {
      text-align: left;
    }
  }
</style>
